package com.CST.service.impl.ys;

import com.CST.common.constant.Constants;
import com.CST.dto.ys.YsDetailDTO;
import com.CST.entity.cb.BdSysUser;
import com.CST.entity.ys.YsAccountDetail;
import com.CST.mapper.cst.cb.BdSysUserMapper;
import com.CST.mapper.cst.ys.YsAccountDetailMapper;
import com.CST.service.ys.YsAccountDetailService;
import com.CST.util.DateStringUtil;
import com.CST.util.ExcelTransfer;
import com.CST.util.HttpUtil;
import com.CST.util.PageHelperTool;
import com.CST.vo.ys.AccountDetailVO;
import com.CST.vo.ys.ExpenseVO;
import com.CST.vo.ys.YsAccountDetailVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author qtx
 * @since 2023-04-21
 */
@Service
public class YsAccountDetailServiceImpl extends ServiceImpl<YsAccountDetailMapper, YsAccountDetail> implements YsAccountDetailService {

    private final YsAccountDetailMapper dao;

    @Autowired
    private BdSysUserMapper userMapper;

    @Autowired
    private ExcelTransfer<AccountDetailVO> excelTransfer;

    public YsAccountDetailServiceImpl(YsAccountDetailMapper dao) {
        this.dao = dao;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public YsAccountDetailVO listBudgetInfo(YsDetailDTO dto, HttpServletRequest res) {
        Optional.ofNullable(dto.getStartTime())
                .orElseThrow(()->new RuntimeException("起始时间不能为空"));
        Optional.ofNullable(dto.getEndTime())
                .orElseThrow(()->new RuntimeException("截止时间不能为空"));
        Optional.ofNullable(dto.getNum())
                .orElseThrow(()->new RuntimeException("页码不能为空"));
        Optional.ofNullable(dto.getSize())
                .orElseThrow(()->new RuntimeException("页大小不能为空"));
        if(!dto.getStartTime().split("-")[0].equals(dto.getEndTime().split("-")[0])){
            throw  new RuntimeException("年份不能跨越");
        }
        BdSysUser user = userMapper.getUserById(HttpUtil.getRequestHeaderInfo(Constants.USER_ID));
        // todo  临时权限
        if (!"ALL".equals(user.getDeptCode())){
            dto.setDeptCode(user.getDeptCode());
        }
        dto.setStart(DateStringUtil.transformer(dto.getStartTime()));
        dto.setEnd(DateStringUtil.transformer(dto.getEndTime()));
        dto.setStartTime(dto.getStartTime().replace("-",""));
        dto.setEndTime(dto.getEndTime().replace("-",""));
        dto.setType(1);
        dto.setSubjectType(5);
        List<AccountDetailVO> accountDetailVOList  = dao.listAccountDetails(dto);

        PageInfo<AccountDetailVO> pageInfo = PageHelperTool.
                excutePageInfo(accountDetailVOList, dto.getNum(), dto.getSize());

        return getYsAccountDetailVO(dto, pageInfo);
    }

    @Override
    public String exportBusinessBudgetList(YsDetailDTO dto, HttpServletResponse response) {
        Optional.ofNullable(dto.getStartTime())
                .orElseThrow(()->new RuntimeException("起始时间不能为空"));
        Optional.ofNullable(dto.getEndTime())
                .orElseThrow(()->new RuntimeException("截止时间不能为空"));
        if(!dto.getStartTime().split("-")[0].equals(dto.getEndTime().split("-")[0])){
            throw  new RuntimeException("年份不能跨越");
        }
        try {
            BdSysUser user = userMapper.getUserById(HttpUtil.getRequestHeaderInfo(Constants.USER_ID));
            // todo  临时权限
            if (!"ALL".equals(user.getDeptCode())){
                dto.setDeptCode(user.getDeptCode());
            }
            dto.setStart(DateStringUtil.transformer(dto.getStartTime()));
            dto.setEnd(DateStringUtil.transformer(dto.getEndTime()));
            dto.setStartTime(dto.getStartTime().replace("-",""));
            dto.setEndTime(dto.getEndTime().replace("-",""));
            dto.setType(1);
            excelTransfer.exportExcel(response, dao.listAccountDetails(dto), "业务预算执行明细(费用类)", "sheet",
                    AccountDetailVO.class);
            return "导出成功";
        }catch (Exception e){
            throw new RuntimeException("导出失败");
        }

    }

    @Override
    public AccountDetailVO getAccountByNum(Integer num,Integer yard,Integer type) {
        Optional.ofNullable(num)
                .orElseThrow(()->new RuntimeException("编码不能为空"));
        Optional.ofNullable(yard)
                .orElseThrow(()->new RuntimeException("院区不能为空"));

        return dao.getAccountByNum(num, yard, type);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public YsAccountDetailVO listExpenseInfo(YsDetailDTO dto) {
        Optional.ofNullable(dto.getStartTime())
                .orElseThrow(()->new RuntimeException("起始时间不能为空"));
        Optional.ofNullable(dto.getEndTime())
                .orElseThrow(()->new RuntimeException("截止时间不能为空"));
        Optional.ofNullable(dto.getNum())
                .orElseThrow(()->new RuntimeException("页码不能为空"));
        Optional.ofNullable(dto.getSize())
                .orElseThrow(()->new RuntimeException("页大小不能为空"));
//        if(!dto.getStartTime().split("-")[0].equals(dto.getEndTime().split("-")[0])){
//            throw  new RuntimeException("年份不能跨越");
//        }
        dto.setStart(DateStringUtil.transformer(dto.getStartTime()));
        dto.setEnd(DateStringUtil.transformer(dto.getEndTime()));
        dto.setStartTime(dto.getStartTime().replace("-",""));
        dto.setEndTime(dto.getEndTime().replace("-",""));
        dto.setType(2);
        dto.setSubjectType(6);
        BdSysUser user = userMapper.getUserById(HttpUtil.getRequestHeaderInfo(Constants.USER_ID));
        // todo  临时权限
        if (!"ALL".equals(user.getDeptCode())){
            dto.setDeptCode(user.getDeptCode());
        }

        List<AccountDetailVO> accountDetailVOList  = dao.listExpenseDetails(dto);

        PageInfo<AccountDetailVO> pageInfo = PageHelperTool.
                excutePageInfo(accountDetailVOList, dto.getNum(), dto.getSize());

        return getYsAccountDetailVO(dto, pageInfo);
    }


    @Override
    public String exportManageExpenseList(YsDetailDTO dto, HttpServletResponse response) {
        Optional.ofNullable(dto.getStartTime())
                .orElseThrow(()->new RuntimeException("起始时间不能为空"));
        Optional.ofNullable(dto.getEndTime())
                .orElseThrow(()->new RuntimeException("截止时间不能为空"));
        if(!dto.getStartTime().split("-")[0].equals(dto.getEndTime().split("-")[0])){
            throw  new RuntimeException("年份不能跨越");
        }
        try {
            dto.setStart(DateStringUtil.transformer(dto.getStartTime()));
            dto.setEnd(DateStringUtil.transformer(dto.getEndTime()));
            dto.setStartTime(dto.getStartTime().replace("-",""));
            dto.setEndTime(dto.getEndTime().replace("-",""));
            dto.setType(2);
            BdSysUser user = userMapper.getUserById(HttpUtil.getRequestHeaderInfo(Constants.USER_ID));
            // todo  临时权限
            if (!"ALL".equals(user.getDeptCode())){
                dto.setDeptCode(user.getDeptCode());
            }

            excelTransfer.exportExcel(response,dao.listExpenseDetails(dto),"管理预算执行明细(费用类)", "sheet",
                    AccountDetailVO.class);
            return "导出成功";
        }catch (Exception e){
            throw new RuntimeException("导出失败");
        }
    }

    @Override
    public AccountDetailVO getAccountById(Long id) {
        return dao.getAccountById(id);
    }


    private YsAccountDetailVO getYsAccountDetailVO(YsDetailDTO dto, PageInfo<AccountDetailVO> pageInfo) {
        List<ExpenseVO> expenseVOList = dao.listExpense(dto);
        BigDecimal total = expenseVOList.stream().
                map(ExpenseVO::getAMOUNT).reduce(BigDecimal.ZERO,BigDecimal::add);
        YsAccountDetailVO vo = new YsAccountDetailVO();
        ExpenseVO evo = new ExpenseVO();
        evo.setSort(0);
        evo.setSubjectName("总费用");
        evo.setAMOUNT(total);
        expenseVOList.add(evo);
        vo.setTotal(total);
        vo.setPageInfo(pageInfo);
        vo.setExpenseVOList(expenseVOList);
        return vo;
    }
}
